package com.richapp.launcher.database.update;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.richapp.launcher.database.update.mode.Update;

import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class UpdateDatabaseHelper extends OrmLiteSqliteOpenHelper {

	private static final int databaseVersion = 1;
	private static UpdateDatabaseHelper instance;
	private static final String TAG = UpdateDatabaseHelper.class.getName();

	private Map<String, Dao> daos = new HashMap<String, Dao>();

	private static Context contextObj = null;

	/**
	 * 获取单例helper
	 * @param context
	 * @return
	 */
	public static synchronized UpdateDatabaseHelper getHelper(Context context){
		if(instance == null){
			synchronized (UpdateDatabaseHelper.class) {
				if(instance == null){
					contextObj = context;
					instance = new UpdateDatabaseHelper(contextObj);
				}
			}
		}
		return instance;
	}

	private UpdateDatabaseHelper(Context context) {
		super(context, Environment.getExternalStorageDirectory()+ File.separator+context.getPackageName()+"/db/update.db", null, databaseVersion);
	}

	
	@Override
	public void onCreate(SQLiteDatabase sd, ConnectionSource cs) {
		try {
			//创建表
            TableUtils.createTableIfNotExists(cs, Update.class);
		} catch (Exception e) {
			Log.v(TAG, e.getMessage());
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sd, ConnectionSource cs, int oldVersion,int newVersion) {
		try {
			//删除表
			TableUtils.dropTable(cs, Update.class, true);

			//创建表
			onCreate(sd, cs);
		} catch (Exception e) {
			Log.v(TAG, e.getMessage());
		}
	}
	
	
	public synchronized Dao getDao(Class clazz) throws SQLException
    {  
        Dao dao = null;  
        String className = clazz.getSimpleName();  
  
        if (daos.containsKey(className))  
        {  
            dao = daos.get(className);  
        }  
        if (dao == null)  
        {  
            dao = super.getDao(clazz);  
            daos.put(className, dao);  
        }  
        return dao;  
    }

	/** 
     * 释放资源 
     */  
    public void close()
    {  
        super.close();  
  
        for (String key : daos.keySet())  
        {  
            Dao dao = daos.get(key);  
            dao = null;  
        }  
    }  
}
